<template>
  <!--  客户投诉管理（区域经理）  -->
  <div>
    <!-- 搜索 -->
    <TopFilter
      ref="commonTopFilter"
      :list="topFilterInit"
      :cols="3"
      labelWidth="90"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
      @resetChange="resetHandle"
    ></TopFilter>


    <!-- 按钮 -->

    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onRowSelectChange="selectChange"
      :isSelectColumn="false"
      :rowstyles="rowStyleData"
      columnsRef="notification_maintain_index_01"
      :onColumnsChange="columns => this.columns = columns"
      :onSyncTableData="syncComplainData"
    >
     <template slot="controls">
       <multiuse-button type="primary" :click="exportFileBtn.bind(this)">导出</multiuse-button>

      </template>
    </FilterTable>


    <!-- 响应窗口 -->
    <Drawer
      :visible.sync="visibleDrawer"
      :title="title"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <detail v-model="initData" :ccResponseData="ccResponseData" @close="infoClose" />
    </Drawer>

     <!--  服务中心选择 -->
    <BaseDialog :visible.sync="selectDelearFlag" title="服务中心选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DealerList @close="Delearclose" @save="Delearsave" selectionType="multiple" />
    </BaseDialog>
  </div>
</template>

<script>
import detail from './detail';
import { deleteNotificationById } from '@/api/cms-api/notification/maintain/index';
import { dictionary } from '@/utils/dictMixin';
import { region } from '@/api/cms-common/region';//行政区域
import { getComplainList,getListForExport} from '@/api/customerRepair/customerComplaint/customerComplaintQuery';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import { getRegion, getCommunity,getLevelOneArea, getLevelTwoAndThreeArea } from '@/api/cms-common/dealerdata/index';//事业部，办事处
import { exportExcelFile } from '@/utils';

export default {
  mixins: [dictionary,region],
  components: {
    //infoModal
    DealerList,
    detail
  },
  props:{
    defaultStatus: {
      type: [String,Array],
      required: false,
      default:()=>{
        return '';
      }
    }
  },
  data() {
    return {
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      fetchApi: getComplainList, //api 接口 table请求数据入口
      fetchParams: null,
      visibleDrawer: false,
      initData: {},
      title: '',
      itemList:{},
      saveLoading: false,
      selectDealerData: [],
      selectDelearFlag: false,
      dealerData: [],
      rowSelectData: [],
      ccResponseData:'',
      rowStyleData:[],
      dealerCompanyCode: [],
      dealerCodeSearch: "",
      actions: { type: '', title: '', visible: false, data: null },
      exportLoading: false, // 导出加载中


    };
  },
  mounted() {
    this.initProvince();
    this.getBigArea();
    // this.BaseTable = this.$refs.table.$refs.pageTable;

  },
  methods: {
    syncComplainData(data,isFirst){
      console.log('data',data)
      if (!data.length) return;
      data.forEach(x => {
        if (x.isRed) {
          this.rowStyleData.push({ row: x, styles: { background: '#ffcccc' } });
        }else{
          this.rowStyleData.push({ row: x, styles: { background: '#fff' } });
        }
      });
    },
    topFilterInitFun() {
      let bt = { required: true, message: '必填', trigger: ['change', 'blur'] };
      let btl = [bt,];
      return [
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: 'VIN'
        },
        {
          type: 'INPUT',
          label: '投诉人手机',
          fieldName: 'cusMobile',
          placeholder: '投诉人手机'
        },
        {
          type: 'INPUT',
          label: '投诉人姓名',
          fieldName: 'cusName',
          placeholder: '投诉人姓名'
        },
        {
          type: 'SELECT',
          label: '投诉类型',
          fieldName: 'ccType',
          itemList: this.createDictList('5586')
        },
        {
          type: 'SELECT',
          label: '投诉等级',
          fieldName: 'ccLevel',
          itemList: this.createDictList('5587')
        },
        {
          type: 'SELECT',
          label: '单据状态',
          fieldName: 'ccState',
          itemList: this.createDictList('5589',[55891007])
        },

        {
          type: 'RANGE_DATE',
          label: '投诉日期',
          fieldName: 'complaintDateFrom|complaintDateTo'
        },
       {
          type: 'INPUT',
          label: '经销服务商',
          render: (p) => {
          return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => this.selectDelearFlag = true} />
              </div>
            );
          },
        },
        {
          type: 'INPUT',
          label: '投诉单号',
          fieldName: 'ccCode',
          placeholder: '投诉编号'
        },
         {
          type: 'INPUT',
          label: '区域经理',
          fieldName: 'regionManager',
          placeholder: '区域经理'
        },
        { type: 'SELECT', label: '大区', fieldName: 'serviceBigArea', placeholder: '请选择', initialValue: ''
            ,itemList: [],
            // change: val => {
            //   this.getBigArea();
            // },
          },
        { type: 'SELECT', label: '省份', fieldName: 'provinceId', placeholder: '请选择', initialValue: '', itemList: [],change: props => this.initCity(props)},
        { type: 'SELECT', label: '城市', fieldName: 'cityId', placeholder: '请选择', initialValue: '', itemList: [], change: props => this.initTown(props)}

      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text"  onClick={() => this.ccResponse(props.row)}>
                  明细
                </el-button>

              </div>
            );
          }
        },
        {
          title: '投诉单号',
          dataIndex: 'ccCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '投诉日期',
          dataIndex: 'ccDate',
          sorter: true,
          filter: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '单据状态',
          dataIndex: 'ccState',
          sorter: true,
          filter: true,
          filterType: 'radio',
          filterItems: this.createDictList(5589),
          dictItems: this.createDictList(5589)
          // render: props => {
          //   return <div>{this.createDictText(props.row.COMPLAINT_KIND, '8213')}</div>;
          // }
        },
        {
          title: '车主姓名',
          dataIndex: 'owenrName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车主手机',
          dataIndex: 'owenrMobile',
          sorter: true,
          filter: true,
          filterType: 'input',
        },

        {
          title: '投诉人姓名',
          dataIndex: 'cusName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '投诉人手机',
          dataIndex: 'cusMobile',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系电话',
          dataIndex: 'cusTel',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          sorter: true,
          filter: true,
          width: 150,
          filterType: 'input',
        },
        {
          title: '车系',
          dataIndex: 'series',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
         {
          title: '车型',
          dataIndex: 'model',
          sorter: true,
          filter: true,
          filterType: 'input',
        },

        {
          title: '车牌号',
          dataIndex: 'license',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '购车时间',
          dataIndex: 'purchaseTime',
          sorter: true,
          filter: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss'

        },
        {
          title: '行驶里程',
          dataIndex: 'mileage',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '投诉渠道',
          dataIndex: 'ccChannel',
          sorter: true,
          filter: true,
          filterType: 'radio',
          filterItems: this.createDictList(5518),
          dictItems: this.createDictList(5518)
        },
        {
          title: '投诉等级',
          dataIndex: 'ccLevel',
          sorter: true,
          filter: true,
          filterType: 'radio',
          filterItems: this.createDictList(5587),
          dictItems: this.createDictList(5587)
        },
        {
          title: '投诉类型',
          dataIndex: 'ccType',
          sorter: true,
          filter: true,
          filterType: 'radio',
          filterItems: this.createDictList(5586),
          dictItems: this.createDictList(5586)
        },


        {
          title: '大区',
          dataIndex: 'serviceBigArea',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filter:true,
          filterType:'input'},
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filter:true,
          filterType:'input'
        },
        {
          title: '区域经理',
          dataIndex: 'regionManager',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
         {
          title: '经销服务商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          width: 160
        },
        {
          title: '经销服务商简称',
          dataIndex: 'dealerShortName',
          sorter: true,
          width: 160
        },
         {
          title: '响应时间',
          dataIndex: 'reAt',
          sorter: true,
          filter: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss'

        },
         {
          title: '处理时间',
          dataIndex: 'opAt',
          sorter: true,
          filter: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss'

        },
         {
          title: '结案时间',
          dataIndex: 'closeDate',
          sorter: true,
          filter: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss'

        },

      ];
    },
   //初始化所在省份
    async initProvince(){
      let pl = await this.createRegionList();
      this.topFilterInit.find(item => item.fieldName === 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId){
      if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterInit.find(item => item.fieldName === 'cityId');
      city.itemList = cl;
      city.initialValue = '';
      //清除区县
      let district = this.topFilterInit.find(item => item.fieldName === 'districtId');
      district.itemList = [];
      district.initialValue = '';
    },
    //初始化所在县市数据
    async initTown(cityId){
      if(!cityId || cityId==null || typeof(cityId)=='undefined'){
        return;
      }
      let td = this.cityData[cityId].children;
      let tl = this.createSubRegionList(td);
      //初始化区县，清除原值
      let district = this.topFilterInit.find(item => item.fieldName === 'districtId');
      district.itemList = tl;
      district.initialValue = '';
    },
    //获取大区
    async getBigArea() {
      const res = await getLevelTwoAndThreeArea(15061020, null);
        if (res.resultCode === 200) {
          this.topFilterInit.find(item => item.fieldName === 'serviceBigArea').itemList = res.data.map(x => ({ value: parseInt(x.orgId), text: x.orgName }));
        }
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);

      console.log('搜索框数据：', this.fetchParams);
      console.log('ccc', this.$route);
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ? this.selectDealerData : null }, { xhrAbort: false });
      console.log('changeHandle=>', val);
      console.log('搜索框数据：', this.fetchParams);


    },
    //展开收起时触发
    collapseHandle() {},
    ccResponse(row) {
      this.title = '客户投诉明细';
      // this.initData = {
      //   notificationId: row.notificationId,
      //   id: 1001
      // }; //行id
      this.ccResponseData = row;
      this.visibleDrawer = true;
    },

    Delearclose() {
      this.selectDelearFlag = false;
    },


    //关闭详情 rData 是页面关闭回调回来的数据
    infoClose(rData) {
      this.visibleDrawer = false;
      if (rData.type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },

    validReturnDate(res) {
      if (res.resultCode === 200) {
        this.saveLoading = false;
        this.$notify.success({ title: '提示信息', message: '操作成功!' });
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      } else {
        this.saveLoading = false;
        this.$notify.error({ title: '提示信息', message: res.errMsg || '操作失败!' });
      }
    },
    selectChange(val) {
      console.log('val', val);
      this.rowSelectData = val;
    },
    // 删除
    async deleteItem(data) {
      this.$confirm('是否删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          console.log('data:', data.notificationId);
          var res = await deleteNotificationById(data.notificationId);
          this.validReturnDate(res);
        })
        .catch(() => {
          this.$notify.info({ title: '提示信息', message: '操作取消' });
        });
    },
     resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCompanyCode: null }, { xhrAbort: false });
    },
    async close(val, type) {
      this.actions.visible = val;
      if (type === 'refresh') {
        const [err, data] = await this.$refs.topFilter.GET_FORM_DATA();
        let params = { ...this.fetchParams, ...val };
        if (params.ownerParCode && params.ownerParCode.length) {
          params.ownerCode = this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue;
        } else {
          params.ownerCode = undefined;
        }
        this.fetchParams = params;
      }
    },
      //保存
    Delearsave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach(item => {
        this.selectDealerData.push(item.dealerCompanyCode);
      });
      this.selectDelearFlag = false;
    },
     // 导出
    async exportFileBtn() {
      let params = { ...this.fetchParams };
      console.log(params, '导出::');
      let res = await getListForExport(params);
      console.log(res.data, '导出::');
      try {
        exportExcelFile(res.data, '客户投诉信息');
      } catch (e) {
        console.log(e, '错误::');
      }
    },
  }
};
</script>

<style lang="less" scoped>
</style>
